const express = require('express')
const { query } = require('../utils/pool')
const router = express.Router()

// 专家添加
router.post('/add', async (req, res, next) => {
  const obj = req.body
  try {
    var result = await query('insert into ih_expert set ?', [obj])
  } catch (err) {
    return next(err)
  }
  console.log(result)
  res.send({ code: 200, msg: '专家添加成功' })
})

// 专家列表
router.get('/list', async (req, res, next) => {
  const obj = req.query;
  if (!obj.pno) obj.pno = 1;
  if (!obj.count) obj.count = 10;
  const size = parseInt(obj.count);
  const start = (obj.pno - 1) * size;
  try {
    let sql
    if (obj.name || obj.hospital_id) {
      let str = ''
      if (!obj.name) {
        str = `hospital_id=${obj.hospital_id}`
      } else if (!obj.hospital_id) {
        str = `name like '%${obj.name}%'`
      } else {
        str = `name like '%${obj.name}%' and hospital_id=${obj.hospital_id}`
      }
      sql = `select a.name,b.title hospital_title,c.title office_title,a.title
      ,a.role,a.header_pic,a.img_charge,a.video_charge,a.num,a.goodat,a.profile,a.id_pic,a.license_pic  from  ih_expert a,ih_hospital b,ih_office c where a.hospital_id=b.id and a.office_id=c.id and (${str}) order by a.id desc limit ?,?; select count(*) as n from ih_expert where ${str}`
    } else {
      sql = `select a.name,b.title hospital_title,c.title office_title,a.title
      ,a.role,a.header_pic,a.img_charge,a.video_charge,a.num,a.goodat,a.profile,a.id_pic,a.license_pic  from  ih_expert a,ih_hospital b,ih_office c where a.hospital_id=b.id and a.office_id=c.id; select count(*) as n from ih_expert`
    }
    var result = await query(
      sql,
      [start, size]
    )
  } catch (err) {
    return next(err)
  };
  console.log(result);
  res.send({
    code: 200,
    msg: '专家列表',
    data: result[0],
    total: result[1][0].n,
    pno: obj.pno
  });
})

// 科室修改
router.put('/update', async (req, res, next) => {
  const obj = req.body
  try {
    var result = await query('update ih_expert set ? where id=?', [obj, obj.id])
  } catch (err) {
    return next(err)
  }
  if (result.changedRows === 0) {
    res.send({ code: 400, msg: '修改失败' })
  } else {
    res.send({ code: 200, msg: '修改成功' })
  }
})
// 删除科室
router.delete('/', async (req, res, next) => {
  const { id } = req.query
  try {
    var result = await query('delete from ih_expert where id=?', [id])
  } catch (err) {
    return next(err)
  }
  if (result.affectedRows === 0) {
    res.send({ code: 400, msg: '删除失败' })
  } else {
    res.send({ code: 200, msg: '删除成功' })
  }
})



module.exports = router